<?php
/**
 * Created by PhpStorm.
 * User: moon
 * Date: 2016/11/22
 * Time: 上午9:05
 * redis cache 类
 */
namespace app\initcore;

use app\addon\appLog;

class Cacheredis
{

    public static $handler = null;


    private static function initCache(){
        if(self::$handler != null){
            return true;
        }
        try {
            self::$handler = new \Redis;
            self::$handler->connect(REDIS_CACHE[0], REDIS_CACHE[1]);    //短连接
        } catch (\Exception $e) {
            $error = [
                'info' => '初始化redis缓存出错！',
                'file' => $e->getFile().':'.$e->getLine(),
                'msg' => $e->getMessage()
            ];
            appLog::appLog('error', $error);   //记录错误日志
            self::$handler = null;
        }
    }
    /**
     * @param $name
     * @param $value
     */
    public static function set($name, $value)
    {
        self::initCache();
        if (self::$handler === null) return null;
        //对数组/对象数据进行缓存处理，保证数据完整性
        $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;

        self::$handler->set($name, $value);
    }//end

    /**
     * @param $name
     * @param $value
     * @param $expire
     */
    public static function setex($name, $value, $expire = null)
    {
        self::initCache();
        if (self::$handler === null) return null;
        //对数组/对象数据进行缓存处理，保证数据完整性
        $value = (is_object($value) || is_array($value)) ? json_encode($value) : $value;
        if (is_int($expire)) {
            self::$handler->setex($name, $expire, $value);
        } else {
            self::$handler->set($name, $value);
        }
    }//end func

    /**
     * @param $name
     * 获取缓存数据
     */
    public static function get($name)
    {
        self::initCache();
        if (self::$handler === null) return null;
        $value = self::$handler->get($name);
        $jsonData = json_decode($value, true);
        // 检测是否为JSON数据 true 返回JSON解析数组, false返回源数据
        return ($jsonData === null || $jsonData === false) ? $value : $jsonData;
    }

    /**
     * 删除缓存
     * @param $name
     */
    public static function delete($name)
    {
        self::initCache();
        if (self::$handler === null) return null;
        self::$handler->delete($name);
    }
}//end class